package org.interfaceadaptation.parameter.expression.converter.impl;

import java.lang.reflect.Method;

import org.interfaceadaptation.InterfaceAdaptationError;
import org.interfaceadaptation.parameter.expression.converter.Converter;
import org.interfaceadaptation.util.ReflectionUtils;

public class ToStringConverter implements Converter {

    private Class<?> from;

    private Method toString;

    public ToStringConverter(Class<?> from) {
        this.from = from;
        this.toString = getToString(from);
    }

    public Class<?> getFromClass() {
        return from;
    }

    public Class<?> getToClass() {
        return String.class;
    }

    
	public Object from(Object value) {
		checkType(value, from);
		Object to = ReflectionUtils.invoke(toString,value) ;
		checkType(to, getToClass());
        return to;
    }

	private void checkType(Object value, Class<?> type) {
		if (!type.isAssignableFrom(value.getClass())) {
			throw new InterfaceAdaptationError("value of class " + value.getClass()+" is not assignable to " + from.getName());
		}
	}

    private Method getToString(Class<?> from) {
        return ReflectionUtils.getMethod(from, "toString");
    }
    
    @Override
    public String toString() {
    	return "from "+ from.getSimpleName() + " to " + String.class.getName();
    }

}